/**
 * Created by LIUBA2 on 8/23/2016.
 */
const mongoose = require("mongoose");
const request = require("request");
const Order = mongoose.model("order");
const JMS = require("../config/jms")
const Merchant = mongoose.model("merchant");
var moment = require('moment');

var config=require("../config/config.js");

exports.listOrders = function () {
    console.log("test o=c");
}
exports.addOrder = function (req, res) {
    var o = new Order(req.body);
    var mId=o.merchant._id;
    request(config.wsGetSingleMerchantStatusUrl+mId,function (err,response,body){
        var b=JSON.parse(body);
        console.log("when submit order, ws get merchant status, the merchant is---"+body)
        if(b.mStatus!=2){
            res.json({error: "添加订单失败"});
        }else{
            o.startTime = moment().add(8,'hours').format();
            o.oStatus = 1;
            var foodCart = req.session.foodCart;
            delete foodCart[mId];
            req.session.foodCart=foodCart;
            console.log(o);
            o.save(function (err) {
                if (!err) {
                    res.json(o);
                }
                else {
                    res.json({error: "添加订单失败"});
                }
            })
        }
    })
}
exports.listOrders = function (req, res) {
    //session中获取用户的cId,再放入搜索条件
    //session 部分，未测
    Order.find({cId: req.session.client._id}).sort("-startTime").exec( function (err, orders) {
        if (!err) {
            res.json(orders);
        }
        else {
            res.json({error: "查询订单列表失败"});
        }
    })


    // var orders = [{
    //     "_id" : "57bdaac34b8f997c37716922",
    //     "oStatus": 2,
    //     "startTime":"2016-08-24T14:10:11.000+0000",
    //     "client": {
    //         "cLocation": "东方软件园",
    //         "cPersonName": "Kinva",
    //         "cTel": "13556155709",
    //     },
    //     "cId": "57bd3b9b4574646c14c399e9",
    //     "mId": "57bd6d4871201dcbdfe2a317",
    //     "merchant": {
    //         "mStark": 9.55,
    //         "mLogoPath": "img/3.jpg",
    //         "mBrand": "KaiFengCai",
    //         "mLocation": "nanRuan",
    //         "mTel": "15007115190",
    //     },
    //     "foodInfo": [
    //         {
    //             "num": 3,
    //             "item": {
    //                 "fStatus": 1,
    //                 "fViewPath": "img/07.jpg",
    //                 "fPrice": 5.3,
    //                 "mId": "57bd6d4871201dcbdfe2a317",
    //                 "fName": "安心油条",
    //                 "_id": "57bd9056ee97a40820f25d1a"
    //             }
    //         },
    //         {
    //             "num": 3,
    //             "item": {
    //                 "fStatus": 1,
    //                 "fViewPath": "img/3.jpg",
    //                 "fPrice": 13,
    //                 "mId": "57bd6d4871201dcbdfe2a317",
    //                 "fName": "太阳蛋",
    //             }
    //         }
    //     ],
    // }];
    // res.json(orders);
}
exports.listComplaint = function (req, res) {
    Order.find({complaint: {$nin: ["",null],$exists:true},cId:req.session.client._id}).sort("-startTime").exec( function (err, orders) {
        if (!err) {
            res.json(orders);
        }
        else {
            res.json({error: "查询投诉订单失败"});
        }
    })
}
exports.scoreAndComplaint = function (req, res) {
    var id = req.params.oId;
    if (req.body.oStark != null) {
        var mOldScore = 0;
        var mOrderCount = 0;
        //分数计算并入merchant库
        Order.findOne({_id: id}, function (err, order) {
            order.oStatus = 3;//完成订单
            order.finishTime =moment().add(8,'hours').format();
            console.log("order....." + order);
            order.oStark = parseInt(req.body.oStark);
            order.save(function (err) {
                Order.find({mId: order.mId,oStatus:3}, function (err, orders) {

                    mOrderCount = orders.length;
                    console.log(mOrderCount + "----");

                    Merchant.findOne({_id: order.mId}, function (err, merchant) {
                        mOldScore = merchant.mStark;
                        mStarkSum=mOldScore * (mOrderCount+9)+ parseInt(req.body.oStark);
                        merchant.mStark =( mStarkSum/ (mOrderCount + 10)).toFixed(1);//
                        console.log("````mOldScore:"+mOldScore);
                        console.log("```mOrderCount:"+mOrderCount);
                        console.log("```req.body.oStark:"+req.body.oStark);
                        //console.log("```((mOldScore * (mOrderCount-1) + 100 + parseInt(req.body.oStark) ):"+mOldScore * (mOrderCount-1) + 100 + parseInt(req.body.oStark));
                        console.log("```(mOrderCount + 10):"+(mOrderCount + 10));
                        console.log("```mStarkSum:"+mStarkSum);
                        console.log("```merchant.mStark:"+merchant.mStark);
                        if (merchant.mStark <= 5) {
                            JMS.send(merchant.mId + "#" + merchant.mStark);
                        }
                        merchant.save(function (err) {
                            if (err) {
                                res.json({error: "分数入库失败"});
                            }
                            else {
                                res.json(order);
                            }
                        })
                    })
                })
            })
        })
    }
    else if (req.body.complaint != null) {
        //发送jms

        //Merchant.findOne({_id: o.mId}, function (err, merchant) {
        Order.findOne({_id: id}, function (err, order) {
            console.log("_id:::" + id);
            JMS.send(id + "#"+ order.merchant.mBrand);
            order.complaint = req.body.complaint;
            order.save(function (err) {
                if (!err) {
                    res.json(order);
                }
                else {
                    res.json({error: "订单更新失败"});
                }
            })
        });
        //})
    }
    else {
        res.json({error: "请求消息有误，请重试！"})
    }
    //o.save(function (err) {
    //    if (!err) {
    //        res.json(o);
    //    }
    //    else {
    //        res.json({error: "订单更新失败"});
    //    }
    //})
}

exports.getComplaintOrderResult = function (req, res) {
    request(config.wsGetComplaintOrderHandleResultUrl+req.params.oId,function (err,response,body) {
        var b=JSON.parse(body);
        res.json(b);
    })
}
